nums_set = {1, 2, 3}
print(f"nums_set={nums_set}")
nums_set.add("4")
print(f"nums_set={nums_set}")


# 创建集合
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}
mixed = {1, "hello", 3.14, (1, 2)}  # 可以包含不同类型的不可变元素

print(fruits)  # {'banana', 'orange', 'apple'} (顺序可能不同)
print(numbers)  # {1, 2, 3, 4, 5}
print(mixed)  # {1, 3.14, (1, 2), 'hello'}

# 空集合 - 特别注意！
empty_set = set()  # 必须这样创建
print(empty_set)  # set()
print(type(empty_set))  # <class 'set'>

# 错误的方式 - 这会创建空字典！
not_a_set = {}
print(type(not_a_set))  # <class 'dict'>


# 利用set对列表数据进行去重
nums = [1, 2, 3, 4, 5, 6, 8, 1, 12, 4, 12, 4, 3, 5, 10]
nums_set = set(nums)
print(f"nums_set={nums_set}")

# 通过字符串创建集合
test_str = "abcde"
str_set = set(test_str)
print(str_set)


# 从元组创建
set_from_tuple = set((1, 2, 2, 3))
print(set_from_tuple)  # {1, 2, 3}


# 集合推导式 [0,1,2,3,4,5,6,7,8,9,10] ==>{0, 64, 4, 36, 100, 16}

squares = {index**2 for index in range(11) if index % 2 == 0}

print(f"squares=={squares}")


names_set = set([1, "susan", ("alice", 29, 100), (4, 5, 6)])
print(f"names_set={names_set}")

if "susan" in names_set:
    print(f"susan在集合{names_set}中")

# 集合的解包
params1, *params2, params3 = names_set
print(f"params1={params1},params2={params2},params3={params3}")


# 集合的批量添加
char_set = {"a", "b", "c"}
print(f"刚创建:{char_set},长度为:{len(char_set)}")

char_set.add("d")  # 利用add单个添加

char_set.update(["e", "f", "g"])
char_set.update(("h", "i", "j"))
char_set.update(
    {"a", "b", "c", "k", "l", "m", "n"}
)  # 结合的特性是值唯一，a,b,c不会再添加进去

print(
    f"char_set通过add和update方法添加之后的新集合为:{char_set},长度为:{len(char_set)}"
)


# 集合的删除操作

fruits = {"apple", "banana", "cherry", "date"}

# remove() - 删除指定元素，元素不存在会报错
fruits.remove("banana")
print(fruits)  # {'cherry', 'date', 'apple'}

# fruits.remove("watermelon") # KeyError: 'watermelon'

# discard() - 删除指定元素，元素不存在不会报错（推荐使用）
fruits.discard("cherry")
print(fruits)  # {'date', 'apple'}

fruits.discard("watermelon")  # 不会报错

# pop() - 随机删除并返回一个元素（因为集合无序）
popped_item = fruits.pop()
print(f"删除了: {popped_item}")
print(fruits)

# clear() - 清空集合
fruits.clear()
print(fruits)  # set()


#
